import { useHistory, useLocation } from 'react-router-dom'
import { useEffect, useRef, useState } from 'react'
import { FormInstance } from 'antd-mobile/es/components/form'
import { InputRef } from 'antd-mobile/es/components/input'
import { NavBar, Form, Input, Button } from 'antd-mobile'
import { LoginForm } from '@/types/data'
import { useDispatch } from 'react-redux'
import { getCode, login } from '@/store/actions/login'
import styles from './index.module.scss'

export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  const formRef = useRef<FormInstance>(null)
  const mobileRef = useRef<InputRef>(null)
  const [time, setTime] = useState(0)
  const timer = useRef(-1)
  const location = useLocation<{ from: string }>()
  const onFinish = async (values: LoginForm) => {
    await dispatch(login(values))
    const { from } = location.state || { from: '/home' }
    history.replace(from)
  }
  const onGetCode = async () => {
    if (time > 0) return
    const current = formRef.current!
    const mobile = current.getFieldValue('mobile')
    const errors = current.getFieldError('mobile')
    if (!mobile || errors.length > 0) {
      mobileRef.current!.focus()
      return
    }
    // 发送请求
    await dispatch(getCode(mobile))
    // 开启倒计时
    setTime(60)
    timer.current = window.setInterval(() => {
      setTime((time) => time - 1)
    }, 1000)
  }

  useEffect(() => {
    if (time === 0) {
      clearInterval(timer.current)
    }
  }, [time])

  useEffect(() => {
    clearInterval(timer.current)
  }, [])

  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}></NavBar>

      {/* 表单 */}
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          onFinish={onFinish}
          validateTrigger={['onChange', 'onBlur']}
          ref={formRef}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}
          >
            <Input
              placeholder="请输入用户名"
              autoComplete="off"
              ref={mobileRef}
            ></Input>
          </Form.Item>

          <Form.Item
            className="login-item"
            extra={
              <span className="code-extra" onClick={onGetCode}>
                {time === 0 ? '发送验证码' : `${time}秒后发送`}
              </span>
            }
            name="code"
            rules={[
              {
                required: true,
                message: '验证码不能为空',
              },
              {
                pattern: /^\d{6}$/,
                message: '验证码格式错误',
              },
            ]}
          >
            <Input placeholder="请输入验证码" autoComplete="off"></Input>
          </Form.Item>
          <Form.Item>
            <Button
              color="primary"
              block
              className="login-submit"
              type="submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
